<script lang="ts">
    import { searchTransactions } from "./api/api";
    import type { TransactionRecord } from "./api/transaction-record";

    let email = $state("");
    let password = $state("");

    // Transaction management state
    let bookTitleFilter = $state("");
    let bookAuthorFilter = $state("");
    let bookIsbnFilter = $state("");
    let borrowerNameFilter = $state("");
    let borrowerEmailFilter = $state("");
    let statusFilter: boolean | undefined = $state(undefined);
    let beginTimeFilter = $state("");
    let endTimeFilter = $state("");

    let currentPage = $state(0);
    let pageSize = 10;
    let sortField = 'borrowDate';
    let sortDirection: 'desc' | 'asc' | undefined = 'desc';

    let transactions: TransactionRecord[] = $state([]);
    let totalPages = $state(0);

    function getPages() {
        return Array.from({ length: totalPages }, (_, i) => i);
    }

    async function loadTransactions() {
        const userInfo = { email, password };
        const response = await searchTransactions(
            undefined, // borrowerId
            undefined, // bookId
            beginTimeFilter || undefined,
            endTimeFilter || undefined,
            statusFilter,
            currentPage,
            pageSize,
            sortField,
            sortDirection,
            userInfo
        );
        
        if (response.data?.success && response.data.data) {
            transactions = response.data.data.content || [];
            totalPages = Math.ceil((transactions.length || 1) / pageSize);
        }
    }

    function goToPage(page: number) {
        currentPage = page;
        loadTransactions();
    }
</script>

<style>
    .transaction-table {
        width: 100%;
        border-collapse: collapse;
    }

    .transaction-table th, .transaction-table td {
        border: 1px solid #ddd;
        padding: 8px;
    }

    .transaction-table tr:nth-child(even) {
        background-color: #f2f2f2;
    }

    .transaction-table th {
        padding-top: 12px;
        padding-bottom: 12px;
        text-align: left;
        background-color: #4CAF50;
        color: white;
    }

    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 16px;
    }

    .page-button {
        margin: 0 4px;
        padding: 8px 12px;
        cursor: pointer;
        border: 1px solid #ccc;
        background-color: #f9f9f9;
    }

    .page-button:hover {
        background-color: #e9e9e9;
    }

    .disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
</style>

<div class="max-w-4xl mx-auto mt-10 p-6 bg-white rounded-xl shadow-md">
    <h2 class="text-2xl font-bold text-gray-800 mb-6">Transaction Management</h2>

    <div class="mb-6 p-4 bg-gray-50 rounded-lg">
        <h3 class="text-lg font-medium text-gray-700 mb-4">Login Credentials</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input type="text" id="email" bind:value={email} 
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                <input type="password" id="password" bind:value={password}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
        </div>
    </div>

    <div class="mb-6">
        <h3 class="text-lg font-medium text-gray-700 mb-4">Search Filters</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
                <label for="book-title" class="block text-sm font-medium text-gray-700 mb-1">Book Title</label>
                <input type="text" id="book-title" bind:value={bookTitleFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="book-author" class="block text-sm font-medium text-gray-700 mb-1">Book Author</label>
                <input type="text" id="book-author" bind:value={bookAuthorFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="book-isbn" class="block text-sm font-medium text-gray-700 mb-1">Book ISBN</label>
                <input type="text" id="book-isbn" bind:value={bookIsbnFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="borrower-name" class="block text-sm font-medium text-gray-700 mb-1">Borrower Name</label>
                <input type="text" id="borrower-name" bind:value={borrowerNameFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="borrower-email" class="block text-sm font-medium text-gray-700 mb-1">Borrower Email</label>
                <input type="text" id="borrower-email" bind:value={borrowerEmailFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                <select id="status" bind:value={statusFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    <option value={null}>All</option>
                    <option value={true}>Returned</option>
                    <option value={false}>Borrowed</option>
                </select>
            </div>
        </div>
        <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label for="begin-time" class="block text-sm font-medium text-gray-700 mb-1">Borrow Date Start</label>
                <input type="datetime-local" id="begin-time" bind:value={beginTimeFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="end-time" class="block text-sm font-medium text-gray-700 mb-1">Borrow Date End</label>
                <input type="datetime-local" id="end-time" bind:value={endTimeFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
        </div>
        <div class="mt-4">
            <button on:click={() => loadTransactions()}
                class="w-full py-2 px-4 bg-indigo-600 text-white font-semibold rounded-md shadow hover:bg-indigo-700 transition duration-200">
                Search
            </button>
        </div>
    </div>

    <div class="flex justify-center mb-6">
        <nav class="inline-flex space-x-2">
            <button on:click={() => goToPage(currentPage - 1)} disabled={currentPage === 0}
                class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition duration-200 flex items-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
                </svg>
                Previous
            </button>

            {#each getPages() as pages}
                {#each [pages] as page}
                    <button on:click={() => goToPage(page)}
                        class="px-4 py-2 {page === currentPage ? 'bg-indigo-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'} rounded-md transition duration-200">
                        {page + 1}
                    </button>
                {/each}
            {/each}

            <button on:click={() => goToPage(currentPage + 1)} disabled={currentPage >= totalPages - 1}
                class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition duration-200 flex items-center">
                Next
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 ml-1" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
                </svg>
            </button>
        </nav>
    </div>

    {#if transactions.length > 0}
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Book Title</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Borrower</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Borrow Date</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Return Date</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {#each transactions as transaction (transaction.id)}
                        {#if typeof transaction.id !== 'undefined'}
                            <tr class="hover:bg-gray-50 transition duration-150 ease-in-out">
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{transaction.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{transaction.book.title}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{transaction.borrower.email}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{new Date(transaction.borrowDate as any).toLocaleString()}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {#if transaction.returnDate}
                                        {new Date(transaction.returnDate as any).toLocaleString()}
                                    {/if}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                        {transaction.status ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                                        {transaction.status ? 'Returned' : 'Borrowed'}
                                    </span>
                                </td>
                            </tr>
                        {/if}
                    {/each}
                </tbody>
            </table>
        </div>
    {/if}
</div>